<template>
  <view class="delivery-container">
    <Form ref="form" :model="formData" :rules="rules"></Form>
    <view v-if="!showFormPage" class="delivery-info">
      <view class="delivery-item">
        <mz-list>
          <mz-list-item :show-arrow="false" title="开启外送">
            <template v-slot:right>
              <switch :checked="openDelivery" @change="switchStatusChange" />
            </template>
          </mz-list-item>
        </mz-list>
      </view>
    </view>
    <view v-if="!showFormPage&&openDelivery" class="delivery-info">
      <view class="delivery-item">
        <view class="label">
          <text>基础信息</text>
        </view>
        <mz-list>
          <mz-list-item title="外送电话" @click="handleShowFormPage('phone')">
            <template v-slot:right>
              <view v-if="showFields.includes('phone')" class="value-wrap">
                <input v-model="formData.phone" :focus="true" type="number" placeholder="请输入外送电话" @blur="handleChangePhone('phone')" />
              </view>
              <view v-else class="value-wrap">
                <text>{{ deliveryData.phone||'请输入外送电话' }}</text>
              </view>
            </template>
          </mz-list-item>
          <mz-list-item title="配送地址" @click="gotoMap">
            <template v-slot:right>
              <view class="value-wrap">
                <text>{{ deliveryData.address || '请选择配送地址' }}</text>
              </view>
            </template>
          </mz-list-item>
        </mz-list>
      </view>

      <view class="delivery-item">
        <view class="label">
          <text>更多外送设置(选填)</text>
        </view>
        <mz-list>
          <mz-list-item title="外送时间">
            <template v-slot:right>
              <view class="value-wrap">
                <TimeRange :value="timeRange" placeholder="不限制" @change="handleTimeChange" />
              </view>
            </template>
          </mz-list-item>
          <mz-list-item title="外送范围(公里)" @click="handleShowFormPage('range')">
            <template v-slot:right>
              <view v-if="showFields.includes('range')" class="value-wrap">
                <input
                  v-model="formData.range"
                  :focus="true"
                  type="number"
                  placeholder="请输入外送范围,最多两位小数"
                  placeholder-class="value-placeholder"
                  @blur="handleChangePrice('range')"
                />
              </view>
              <view v-else class="value-wrap">
                <text v-if="deliveryData.range">{{ deliveryData.range }}公里</text>
                <text v-else>不限制</text>
              </view>
            </template>
          </mz-list-item>
          <mz-list-item title="外送费(元)" @click="$goto('/pages/delivery/deliveryFee/deliveryFee')">
            <template v-slot:right>
              <view class="value-wrap">
                <text>{{ deliveryFee }}</text>
              </view>
            </template>
          </mz-list-item>
          <mz-list-item title="起送价(元)" @click="handleShowFormPage('startPrice')">
            <template v-slot:right>
              <view v-if="showFields.includes('startPrice')" class="value-wrap">
                <input
                  v-model="formData.startPrice"
                  :focus="true"
                  type="number"
                  placeholder="请输入起送价,最多两位小数"
                  placeholder-class="value-placeholder"
                  @blur="handleChangePrice('startPrice')"
                />
              </view>
              <view v-else class="value-wrap">
                <text>{{ deliveryData.startPrice||'0.00'|formatPrice }}元</text>
              </view>
            </template>
          </mz-list-item>
          <mz-list-item title="打包费(元)" @click="handleShowFormPage('boxFee')">
            <template v-slot:right>
              <view v-if="showFields.includes('boxFee')" class="value-wrap">
                <input
                  v-model="formData.boxFee"
                  :focus="true"
                  type="number"
                  placeholder="请输入打包费,最多两位小数"
                  placeholder-class="value-placeholder"
                  @blur="handleChangePrice('boxFee')"
                />
              </view>
              <view v-else class="value-wrap">
                <text>{{ deliveryData.boxFee||'0.00'|formatPrice }}元</text>
              </view>
            </template>
          </mz-list-item>
          <mz-list-item title="外送码" @click="openDialog">
            <template v-slot:right>
              <view class="value-wrap">
                <text>点击查看</text>
              </view>
            </template>
          </mz-list-item>
        </mz-list>
      </view>
    </view>
    <FormPage v-if="showFormPage" :field="formField" @submit="handleChange" />
    <uni-popup ref="deliveryPop" type="dialog" @change="handleChangePopup">
      <Code />
    </uni-popup>
    <SaveButton v-if="!showFormPage&&openDelivery" text="保存" @click.native="handleSave" />
  </view>
</template>

<script>
import { mapState, mapGetters, mapActions, mapMutations } from "vuex";
import { Throttle } from "../../utils/index";
import TimeRange from "../../components/public/TimeRange/index.vue";
import FormPage from "./components/FormPage.vue";
import SaveButton from "../../components/public/Button/SaveButton.vue";
import Form from "../../components/public/Form/index.vue";
import Code from "./components/Code.vue";
export default {
  components: {
    TimeRange,
    FormPage,
    SaveButton,
    Form,
    Code
  },
  data() {
    return {
      canBack: false,
      openDelivery: true, // 是否开启外送
      switchChecked: true,
      showFormPage: false,
      isFirst: true, // 是否为第一次开通
      showDeliveryPop: false, // 是否打开二维码弹窗
      pageType: "home",
      formField: "",
      showFields: [],
      rules: {
        phone: [
          { required: true, message: "请填写外送电话", length: 11 },
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请填写正确的手机号格式"
          }
        ],
        address: {
          required: true,
          message: "请选择外送地址"
        }
      },
      formData: {
        phone: "",
        address: "",
        isDelivery: 1,
        latitude: "",
        longitude: "",
        startTime: "",
        endTime: "",
        range: 0,
        startPrice: 0,
        boxFee: 0,
        deliveryFeeConfig: null
        // deliveryFeeConfig: [
        //   {
        //     type: "",
        //     price: "",
        //     config: {
        //       min: "",
        //       max: "",
        //       price: ""
        //     }
        //   }
        // ]
      }
    };
  },
  computed: {
    ...mapState({
      deliveryData: state => state.delivery.data
    }),
    ...mapGetters({ activeShop: "activeShop" }),
    isDelivery() {
      return (this.activeShop && this.activeShop.isDelivery) || 0;
    },
    timeRange() {
      if (this.formData.startTime && this.formData.endTime) {
        let startTime = this.formData.startTime.split(":");
        let endTime = this.formData.endTime.split(":");
        if (startTime.length > 2) {
          startTime.splice(2, 1);
        }
        startTime = startTime.join(":");
        if (endTime.length > 2) {
          endTime.splice(2, 1);
        }
        endTime = endTime.join(":");
        return [startTime, endTime];
      } else {
        return [];
      }
    },
    deliveryFee() {
      if (!this.deliveryData.deliveryFeeConfig) {
        return "0.00元";
      } else if (
        this.deliveryData.type == "fix" ||
        this.deliveryData.deliveryFeeConfig.type == "fix"
      ) {
        return this.deliveryData.deliveryFeeConfig.price + "元";
      } else {
        return this.deliveryData.deliveryFeeConfig.config[0].price + "元起";
      }
    }
  },
  watch: {
    isDelivery(val) {
      this.openDelivery = this.isDelivery == 1 ? true : false;
    }
  },
  onLoad() {
    this.openDelivery = this.isDelivery == 1 ? true : false;
    this.init();
  },
  onBackPress() {
    // 判断是否为表单页
    if (this.showDeliveryPop) {
      this.showDeliveryPop = false;
      this.$refs.deliveryPop.close();
      return true;
    } else {
      if (this.canBack) {
        return false;
      } else {
        uni.showModal({
          title: "提示",
          cancelText: "离开",
          confirmText: "继续填写",
          content: "需要将基础信息填写完整才能开通外送服务哦，确定返回么？",
          success: res => {
            if (!res.confirm) {
              this.canBack = true;
              this.$back();
            }
          }
        });
        return true;
      }
    }
  },
  methods: {
    ...mapMutations({
      SET_DELIVERY_DATA: "SET_DELIVERY_DATA"
    }),
    ...mapActions({
      postDelivery: "postDelivery",
      getDelivery: "getDelivery",
      postDeliveryActive: "postDeliveryActive",
      getShops: "getShops"
    }),
    init() {
      // this.formData = this.deliveryData;
      uni.showLoading({ mask: true });
      this.getDelivery()
        .then(res => {
          if (res.code) {
            this.isFirst = true;
            this.canBack = false;
          } else {
            this.isFirst = false;
            this.canBack = true;
            this.formData = res.data;
            this.formData.isDelivery = 1;
          }
          this.SET_DELIVERY_DATA(this.formData)
        })
        .finally(() => {
          uni.hideLoading();
        });
    },
    // 打开二维码框
    openDialog() {
      this.$refs.deliveryPop.open();
    },
    // 弹框状态更改
    handleChangePopup(e) {
      this.showDeliveryPop = e.show;
    },
    gotoMap() {
      uni.chooseLocation({
        success: res => {
          console.log(res);

          // console.log("位置名称：" + res.name);
          // console.log("详细地址：" + res.address);
          // console.log("纬度：" + res.latitude);
          // console.log("经度：" + res.longitude);
          let form = { address: "", latitude: "", longitude: "" };
          form.address = res.address;
          form.latitude = res.latitude;
          form.longitude = res.longitude;
          // this.SET_DELIVERY_DATA(form);
          this.handleChange(form);
        }
      });
    },
    handleTimeChange(value) {
      let timeRange = {
        startTime: value[0],
        endTime: value[1]
      };
      this.handleChange(timeRange);
    },
    handleShowFormPage(field) {
      this.showFields.push(field);
      // this.formField = field;
      // this.showFormPage = true;
    },
    handleChange(data) {
      this.showFormPage = false;
      for (let key in data) {
        this.formData[key] = JSON.parse(JSON.stringify(data[key]));
      }
      this.SET_DELIVERY_DATA(data);
      // if (!this.isFirst) this.handleSave();
    },
    // 保存外送设置
    handleSave() {
      let formData = this.deliveryData;
      formData.isDelivery = 1;
      uni.showLoading();
      this.$refs.form.validate(valid => {
        if (valid) {
          this.postDelivery(formData).then(res => {
            if (!res.code) {
              uni.showToast({
                icon: "none",
                title: "保存成功"
              });
              uni.hideLoading();
              this.canBack = true;
              this.$back();
            }
          });
        }
      });
    },
    // 修改外送开启状态
    switchStatusChange(e) {
      let params = {
        status: e.detail.value ? 1 : 0
      };
      this.openDelivery = e.detail.value;
      if (this.isFirst) {
      } else {
        uni.showLoading();
        this.postDeliveryActive(params)
          .then(res => {
            if (!res.code) {
              this.getShops();
            }
          })
          .finally(() => {
            uni.hideLoading();
          });
      }
    },
    handleChangePrice(key) {
      if (this.formData[key] || this.formData[key] === 0) {
        let value = Number(this.formData[key]);
        this.formData[key] = parseFloat(value.toFixed(2));
        let obj = {};
        obj[key] = this.formData[key];
        this.SET_DELIVERY_DATA(obj);
      }
      this.showFields = [];
    },
    handleChangePhone(key) {
      let obj = { phone: this.formData.phone };
      this.SET_DELIVERY_DATA(obj);
      this.showFields = [];
    }
  }
};
</script>

<style lang="scss">
.delivery-container {
  padding-bottom: 120rpx;
  .value-placeholder {
    font-size: 24rpx;
  }
  .delivery-item {
    .label {
      padding: 20rpx;
      font-size: $uni-font-size-sm;
      color: $uni-text-color-grey;
    }
    .value-wrap {
      display: flex;
      color: $uni-text-color-grey;
      max-width: 500rpx;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      text-align: right;
    }
  }
}
</style>
